import React, {useEffect, useRef} from "react"
import {drawRuler, polyfillHiDPI} from './utils'

interface CanvasRulerProps {
    vertical: boolean;
    start: number;
    width: number;
    height: number;
    canvasConfig: {
        bgColor: string;
        fontColor: string;
        longMarkColor: string;
        shortMarkColor: string;
    };
    onClick?: React.MouseEventHandler<HTMLCanvasElement>;
    onMouseEnter?: React.MouseEventHandler<HTMLCanvasElement>;
    onContextMenu?: React.MouseEventHandler<HTMLCanvasElement>, 
    onMouseMove?: React.MouseEventHandler<HTMLCanvasElement>;
    onMouseLeave?: React.MouseEventHandler<HTMLCanvasElement>;
}

export default function CanvasRuler(props: CanvasRulerProps) {
    const {vertical, start, width, height, canvasConfig} = props;
    const {onClick, onMouseEnter, onContextMenu, onMouseMove, onMouseLeave} = props;

    const canvasRef = useRef<HTMLCanvasElement>();

    useEffect(() => {
        const canvasElement = canvasRef.current;

        const ctx = polyfillHiDPI(canvasElement, width, height);

        if (vertical) {
            drawRuler(true, ctx, start, width, height, canvasConfig)
        } else {
            drawRuler(false, ctx, start, width, height, canvasConfig)
        }

    }, [width, height]);

    return (
        <canvas
            ref={canvasRef}
            className="canvas-ruler"
            onClick={onClick}
            onMouseEnter={onMouseEnter}
            onContextMenu={onContextMenu}
            onMouseMove={onMouseMove}
            onMouseLeave={onMouseLeave}
        />
    );
}
